package com.ratingbay.console.web.controller;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ratingbay.cache.*;
import com.ratingbay.console.api.*;
import com.ratingbay.console.dataface.*;
import com.ratingbay.console.common.*;

@Controller
public class BaseController {
    protected Logger logger = LogManager.getLogger(this.getClass());
    protected CacheManager cacheManager = CacheManager.getInstance();

    //used in class inner
    private ApiComponent apiComponent = null;
    private ApiComponent getApiComponent(){
        if(null == apiComponent){
            apiComponent = ApiComponent.getInstance();
        }
        return apiComponent;
    }
    

    //public api
    private TwitterUserApi tUserApi = null;
    public TwitterUserApi getTUserApi(){
        if(null == tUserApi){
            tUserApi = TwitterUserApi.getInstance( ServiceComponent.getInstance().getTwitterUserService(), 
            new HttpSessionImpl(getSession()) );
        }
        return tUserApi;
    }
    public TweetApi getTweetApi(){
        return getApiComponent().getTweetApi();
    }
    public GameApi getGameApi(){
        return getApiComponent().getGameApi();
    }
    public LinkApi getLinkApi(){
        return getApiComponent().getLinkApi();
    }
    public WordApi getWordApi(){
        return getApiComponent().getWordApi();
    }
    public InfluentialUserApi getIUserApi(){
        return getApiComponent().getIUserApi();
    }


    // base methods
    public HttpSession session;
    public HttpSession getSession() {
        if(null == this.session){
            ServletRequestAttributes attrs = 
            (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = attrs.getRequest() ;
            this.session = request.getSession();
        }
        return this.session;
    }

    private boolean isLogged = false;
    public boolean getIsLogged(){
        if(null != getSession().getAttribute("userId")){
            return true;
        }
        return false;
    }
    
    public ITwitterUser getITwitterUser(){
        return getTUserApi().getITwitterUser();
    }
}